package com.blast.comicsisland.activity;

import android.os.AsyncTask;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;

import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import com.blast.comicsisland.R;
import com.blast.comicsisland.adapters.ContentPagerAdapter;
import com.blast.comicsisland.model.commic.commiccontent.Info;
import com.blast.comicsisland.utils.JsonUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * 漫画的实际内容页 应使用FrameLayout布局 设置菜单默认显示不可见 下层使用ViewPager
 * 内部为ImageView 通过Url加载图片 应写入三级缓存 setLimit至少等于4
 * 菜单至少包含亮度调节与SeekBar跳转
 */
public class ContentActivity extends AppCompatActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {
    private RadioGroup radioGroup;
    private RelativeLayout relativeLayout;
    private ViewPager viewPager;
    private TextView back;
    private TextView title;
    private String url;
    private LinearLayout loading;
    boolean isNode = true;
    private List<Info> list;
    private ContentPagerAdapter adapter;
    private String bookId;
    private String partId;
    private String partVersion;
    boolean isLoading=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);

        setContentView(R.layout.activity_content);
        radioGroup = (RadioGroup)findViewById(R.id.content_radiogroup);
        relativeLayout = (RelativeLayout)findViewById(R.id.toolbar_layout);
        title = (TextView)findViewById(R.id.content_item_title_text);
        loading = (LinearLayout)findViewById(R.id.ll_rublish_sms_info_loading);
        viewPager = (ViewPager)findViewById(R.id.content_viewpager);
        viewPager.setOffscreenPageLimit(10);
        back = (TextView)findViewById(R.id.content_back);
        list = new LinkedList<>();
        adapter = new ContentPagerAdapter(list);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(this);

        back.setOnClickListener(this);




        Bundle bundle = getIntent().getExtras();
        String name = bundle.getString("name");
        if (name!=null){
            title.setText(name);
        }
        if (bundle!=null){
            bookId = bundle.getString("bookId");
            partId = bundle.getString("partId");
            partVersion = bundle.getString("partVersion");
            Log.d("partId_prevours",partId);
            url = "http://mhjk.1391.com/comic/comicsread_v3?bookid="
                    + bookId
                    +"&partid="
                    + partId
                    +"&partVersion="
                    + partVersion
                    +"&e="
                    +System.currentTimeMillis()/1000
                    +"&channelid=baidu";
            Log.d("url",url);
            new ContentTask().execute(url);
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    /**
     * 仔细分析onPageScrollStateChanged(int i)的参数i可知：
     * i=2时为页面切换状态，在当前页面滑动一点没有切换页面，
     * 同样有2这个状态，只有到最后一页还要向下一页切换时不会经历2这个状态。
     * @param state
     */
    @Override
    public void onPageScrollStateChanged(int state) {
        /**
         * 正常滚动时 1-2-0
         * 1-isNode=true
         * 2-isNode=false
         * 0&&isNode = false 不是末尾或开始
         *
         * 滚动到末尾或开始时1-0
         * 1-isNode=true
         * 0&&isNode=true
         * 判断是章节头部还是末尾 执行异步任务加载下一个章节
         */

        if (state==2){//1表示正在滚动 2表示滚动完毕 最后一页不能滚动完毕
                        //0表示什么都没做 顺序为1,2,0
            isNode = false;
        }else if(state==0&&isNode){
            //TODO 执行加载下一章节的操作
            //如果是最后一页
            if (viewPager.getCurrentItem()==list.size()-1){
                partId = Integer.toString(Integer.parseInt(partId) + 1);
                Log.d("partId",partId);
                if (!isLoading) {
                    isLoading=true;
                    url = "http://mhjk.1391.com/comic/comicsread_v3?bookid="
                            + bookId
                            + "&partid="
                            + partId
                            + "&partVersion="
                            + partVersion
                            + "&e="
                            + System.currentTimeMillis() / 1000
                            + "&channelid=baidu";
                    Log.d("url",url);
                    new ContentTask().execute(url);
                }
            }
        }else{
            isNode = true;
        }
    }


    class ContentTask extends AsyncTask<String,Void,List<Info>> implements ContentPagerAdapter.OnImageClickListener {

        @Override
        protected List<Info> doInBackground(String... params) {
            List<Info> infoList = null;
            if (params.length>0){
                String str = JsonUtils.stringToRegex(JsonUtils.doGetRequest(params[0]));
                //===============================test
                try {
                    JSONObject object = new JSONObject(str);
                    JSONArray array = object.getJSONArray("info");
                    infoList = new LinkedList<>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject infoObject = array.getJSONObject(i);
                        String width = infoObject.optString("width");
                        String height = infoObject.optString("height");
                        String imgurl = infoObject.getString("imgurl");
                        String referer = infoObject.optString("referer");
                        Info info = new Info();
                        info.setWidth(width);
                        info.setHeight(height);
                        info.setImgurl(imgurl);
                        info.setReferer(referer);
                        infoList.add(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //===============================
            }
            return infoList;
        }

        @Override
        protected void onPostExecute(List<Info> infos) {
            loading.setVisibility(View.INVISIBLE);
            if (infos!=null){
                list.clear();
                list.addAll(infos);
                adapter.setListener(this);
                adapter.notifyDataSetChanged();
                isLoading=false;
            }
        }

        @Override
        protected void onPreExecute() {
            loading.setVisibility(View.VISIBLE);
        }

        @Override
        public void onClick(View v) {
            if (v instanceof NetworkImageView){
                if (radioGroup.getVisibility()==View.INVISIBLE) {
                    radioGroup.setVisibility(View.VISIBLE);
                    relativeLayout.setVisibility(View.VISIBLE);
                }else {
                    radioGroup.setVisibility(View.INVISIBLE);
                    relativeLayout.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){

            case R.id.content_back:
                finish();
                break;
        }
    }
}
